package com.gs.xbinfomytest.util;

import com.gs.xbinfomytest.entity.SysMenu;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Created : IntelliJ IDEA.
 * @ProjectName: xbinfomytest
 * @Package: com.gs.xbinfomytest.util
 * @Author: guoshuai
 * @CreateDate: 2019/8/20 20:56
 * @Description: java类的作用描述
 * @Vsersion: 1.0
 */
public class MenuUtils {

    /**
     * 获取树形菜单
     * @param list
     * @return
     */
    public static List<SysMenu>  getTreeMeauInfo(List<SysMenu>  list){
     List<SysMenu> rootMenu = getRootMenuInfo(list);
     for(SysMenu sysMenu : rootMenu){
         sysMenu.setChildren(getChild(sysMenu.getMenuId(),list));
     }
      return rootMenu;
    }

    //递归，建立子树形结构
    /**
     * 递归查找子菜单
     *
     * @param id
     *            当前菜单id
     * @param list
     *            要查找的列表
     * @return
     */
    private static List<SysMenu> getChild(Long id, List<SysMenu> list) {
        // 子菜单
        List<SysMenu> childList = new ArrayList<>();
        for (SysMenu menu : list) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!StringUtils.isEmpty(menu.getParentId())) {
                if (menu.getParentId()==id) {
                    childList.add(menu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (SysMenu menu : childList) {// 没有url子菜单还有子菜单
            if (!StringUtils.isEmpty(menu.getUrl())) {
                // 递归
                menu.setChildren(getChild(menu.getMenuId(), list));
            }
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }



    public static List<SysMenu>  getRootMenuInfo(List<SysMenu>  list){
        List<SysMenu> rootMenu = new ArrayList<>();
        for (SysMenu sysMenu : list) {
            if(sysMenu.getParentId() == 0){
                rootMenu.add(sysMenu);
            }
        }
       return rootMenu;
    }





}
